package fido

import (
	"bytes"
	"log"

	"github.com/keys-pub/go-libfido2"
)

// todo errors

func Setup(rpID, pin string, cdh []byte) []byte {
	locs, err := libfido2.DeviceLocations()
	if err != nil {
		log.Fatal(err)
	}
	if len(locs) == 0 {
		log.Fatal("No devices")
		return []byte{}
	}

	path := locs[0].Path
	device, err := libfido2.NewDevice(path)
	if err != nil {
		log.Fatal(err)
	}

	attest, err := device.MakeCredential(
		cdh,
		libfido2.RelyingParty{
			ID:   rpID,
			Name: "hmac-secret",
		},
		libfido2.User{
			ID:   bytes.Repeat([]byte{0x01}, 16),
			Name: "hmac-secret",
		},
		libfido2.ES256,
		pin,
		&libfido2.MakeCredentialOpts{
			Extensions: []libfido2.Extension{libfido2.HMACSecretExtension},
			RK:         libfido2.True,
		},
	)
	if err != nil {
		log.Fatal(err)
	}

	return attest.CredentialID
}

func GetHmacSecret(rpID, pin string, cdh, salt, credID []byte) []byte {
	locs, err := libfido2.DeviceLocations()
	if err != nil {
		log.Fatal(err)
	}
	if len(locs) == 0 {
		log.Fatal("No devices")
		return []byte{}
	}

	path := locs[0].Path
	device, err := libfido2.NewDevice(path)
	if err != nil {
		log.Fatal(err)
	}
	assertion, err := device.Assertion(
		rpID,
		cdh,
		[][]byte{credID},
		pin,
		&libfido2.AssertionOpts{
			Extensions: []libfido2.Extension{libfido2.HMACSecretExtension},
			HMACSalt:   salt,
		},
	)
	if err != nil {
		log.Fatal(err)
	}

	return assertion.HMACSecret
}
